package com.itheima.leyou.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Map;

@Repository
public class UserDao {

    @Resource
    JdbcTemplate jdbcTemplate;

    @Autowired
    RestTemplate restTemplate;

    public ArrayList<Map<String, Object>> getUser(String username, String password){
        //1、创建查询会员sql
        String sql = "select id, username, password, phone " +
                "from tb_user where username = "+username;

        //2、执行sql并返回
        return (ArrayList<Map<String, Object>>) jdbcTemplate.queryForList(sql);
    }

    public int insertUser(String username, String password){

        String now = restTemplate.getForObject("http://leyou-time-server/getTime", String.class);

        //1、创建写入会员的SQL
        final String sql = "insert into tb_user (username, password, phone, create_time) " +
                "values ('"+username+"', '"+password+"', '"+username+"', '"+now+"')";

        //2、执行会员的SQL
        KeyHolder keyHolder = new GeneratedKeyHolder();
        final String finaSql = sql;
        boolean result = jdbcTemplate.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement preparedStatement = connection.prepareStatement(finaSql, Statement.RETURN_GENERATED_KEYS);
                return preparedStatement;
            }
        }, keyHolder)==1;

        //3、获取会员id
        return keyHolder.getKey().intValue();
    }
}
